package model

import (
	"go-task/dao"
	"gorm.io/gorm"
)

type TimeTask struct {
	Id              int64  `json:"id" gorm:"primary_key;autoIncrement"`
	TaskId          string `json:"taskId"`
	TaskName        string `json:"taskName"`
	TaskGroup       string `json:"taskGroup"`
	TaskStatus      int    `json:"taskStatus"` // 1-run 2-stop
	TaskType        string `json:"taskType"`   // 任务类型：onetime-运行一次 repeat-重复执行
	CronExpr        string `json:"cronExpr"`
	SubType         string `json:"subType"` // 订阅类型：SHARED-共享 EXCLUSIVE-独占
	TaskData        string `json:"taskData"`
	TaskExtendParam string `json:"taskExtendParam"`
	UpdateTime      string `json:"updateTime"`
	CreateTime      string `json:"createTime"`
}

func (TimeTask) TableName() string {
	return "time_task"
}

func (t TimeTask) AddTask(task *TimeTask) error {
	return dao.DB.Create(task).Error
}

func (t TimeTask) QueryList() (taskList []TimeTask, err error) {
	if err := dao.DB.Find(&taskList).Error; err != nil {
		return nil, err
	}
	return taskList, nil
}

func (t TimeTask) UpdateTaskStatus(taskId string, taskStatus int, exec func() error) error {
	return dao.DB.Transaction(func(tx *gorm.DB) error {
		execErr := exec()
		if execErr != nil {
			return execErr
		}
		db := tx.Model(t)
		db = db.Where("task_id = ?", taskId)
		return db.Updates(map[string]interface{}{"task_status": taskStatus}).Error
	})
}

func (t TimeTask) QueryTask(taskId string) (task *TimeTask, err error) {
	if err := dao.DB.Last(&task, "task_id = ?", taskId).Error; err != nil {
		return nil, err
	}
	return task, nil
}

func (t TimeTask) DeleteTask(taskId string) error {
	return dao.DB.Where("task_id = ?", taskId).Delete(t).Error
}
